package com.ls.config;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.internal.OSSHeaders;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.StorageClass;
import com.ls.utils.Const;
import org.springframework.web.multipart.MultipartFile;

public class AliYunConfig {

    private static OSS ossClient = null;

//    public static void main(String[] args_) throws Exception {
//        Client client = AliYunConfig.createClient();
//        RecognizeCharacterRequest recognizeCharacterRequest = new RecognizeCharacterRequest()
//                .setImageURL("https://xiaoye999.oss-cn-hangzhou.aliyuncs.com/2.jpg")
//                .setMinHeight(10);
//        // 复制代码运行请自行打印 API 的返回值
//        System.out.println(client.recognizeCharacter(recognizeCharacterRequest));
//    }

    /**
     * 上传头像
     * @param file
     * @param prefix
     * @return
     * @throws IOException
     */
    public static String uploadImage(MultipartFile file,String prefix) throws IOException {

        ossClient = new OSSClientBuilder().build(Const.END_POINT, Const.ACCESS_KEY_ID, Const.ACCESS_KRY_SECRET);
        // 创建OSSClient实例。
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        // 获取文件的后缀名
        String suffixName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        // 生成上传文件名
        String finalFileName = System.currentTimeMillis() + "" + new SecureRandom().nextInt(0x0400) + suffixName;
        String objectName = prefix + "/" +sdf.format(new Date()) + "/" + finalFileName;
        // 如果需要上传时设置存储类型和访问权限，请参考以下示例代码。
        PutObjectRequest putObjectRequest = new PutObjectRequest(Const.BUCKET_NAME, objectName, new ByteArrayInputStream(file.getBytes()));
        ObjectMetadata metadata = new ObjectMetadata();
        //存储类型(标准型)
        metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
        //文件类型
        metadata.setHeader(OSSHeaders.CONTENT_TYPE,file.getContentType());
        //读写权限
        metadata.setObjectAcl(CannedAccessControlList.PublicReadWrite);
        //添加请求头
        putObjectRequest.setMetadata(metadata);
        //上传文件
        ossClient.putObject(putObjectRequest);
        //关流
        ossClient.shutdown();
        return objectName;
    }

    public void download(){

    }

}
